package com.nn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nn.R;
import com.nn.constents.SystemConstants;
import com.nn.entity.Article;
import com.nn.entity.Category;
import com.nn.mapper.CategoryMapper;
import com.nn.service.ArticleService;
import com.nn.service.CategoryService;
import com.nn.utils.BeanCopyUtils;
import com.nn.utils.WebUtils;
import com.nn.vo.CategoryListAllVO;
import com.nn.vo.ExcelCategoryVo;
import com.nn.vo.HotCategoryVo;
import com.nn.vo.PageVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 分类表(Category)表服务实现类
 *
 * @author 年年
 * @since 2022-11-11 20:09:24
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private ArticleService articleService;

    /**
     * 获取分类信息（只显示有发布文章的)
     * @author 年年
     * @return
     */
    @Override
    public R getCategoryList() {
        //查询文章表已发布的文章
        LambdaQueryWrapper<Article> articleWrapper =new LambdaQueryWrapper<>();
        articleWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleService.list(articleWrapper);
        //获取文章分类id去重
        Set<Long> categoryIDs = articleList.stream()
                .map(Article::getCategoryId)
                .collect(Collectors.toSet());
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Category::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL)
                .eq(Category::getDelFlag,SystemConstants.ARTICLE_STATUS_NORMAL)
                .in(Category::getId,categoryIDs);
        List<Category> list = list(queryWrapper);
        List<HotCategoryVo> result = BeanCopyUtils.copyBeanList(list, HotCategoryVo.class);
        return R.okResult(result);
    }


    /**
     * 获取所有分类名
     * @return
     */
    @Override
    public R getListAllCategory() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getStatus,0).eq(Category::getDelFlag,0);
        List<Category> categoryInfo = getBaseMapper().selectList(queryWrapper);
        List<CategoryListAllVO> resultList = BeanCopyUtils.copyBeanList(categoryInfo, CategoryListAllVO.class);
        resultList.forEach(o->o.setStatus(null));
        return R.okResult(resultList);
    }


    /**
     * 分页信息分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param status
     * @return
     */
    @Override
    public R pageList(Integer pageNum, Integer pageSize, String name, String status) {
        Page<Category> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(name!=null,Category::getName,name)
                .eq(status!=null,Category::getStatus,status)
                .eq(Category::getDelFlag,0);
        page(page,queryWrapper);
        List<CategoryListAllVO> pageInfo = BeanCopyUtils.copyBeanList(page.getRecords(), CategoryListAllVO.class);
        PageVO pageVO = new PageVO(pageInfo,page.getTotal());
        return R.okResult(pageVO);
    }


    /**
     * 插入分类信息
     * @param category
     * @return
     */
    @Override
    public R insertCategory(Category category) {
        if(!StringUtils.hasText(category.getName()))
            return R.errorResult(504,"分类名不能为空");
        getBaseMapper().insert(category);
        return R.okResult();
    }


    /**
     * 批量删除分类
     * @param ids
     * @return
     */
    @Override
    public R deleteByList(List<Integer> ids) {
        getBaseMapper().deleteBatchIds(ids);
        return R.okResult();
    }

    @Override
    public R getCategoryById(Long id) {
        Category categoryInfo = getBaseMapper().selectById(id);
        CategoryListAllVO result = BeanCopyUtils.copyBean(categoryInfo, CategoryListAllVO.class);
        return R.okResult(result);
    }


    /**
     * 修改分类信息
     * @return
     */
    @Override
    public R updateCategory(Category category) {
        if(!StringUtils.hasText(category.getName()))
            return R.errorResult(504,"分类名不能为空！");
        this.updateById(category);
        return R.okResult();
    }


    /**
     * 导出表格
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //设置下载文件的请求头
        try {
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            //导出所有分类数据
            LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            List<Category> vo = getBaseMapper().selectList(lambdaQueryWrapper);
            List<CategoryListAllVO> resultVO = BeanCopyUtils.copyBeanList(vo, CategoryListAllVO.class);
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(resultVO);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

